/**
 * Copyright &copy; 2013-2015 山东易科德软件有限公司 All rights reserved.
 */
package cn.net.ecode.common.persistence.interceptor;

import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Plugin;
import org.apache.ibatis.plugin.Signature;

import java.util.Properties;

/**
 * 数据表更新前执行的拦截器
 * @author ThinkGem
 * @version 2015-4-28
 */
@Intercepts({@Signature(type = Executor.class, method = "update",
	args = {MappedStatement.class, Object.class})})
public class PreUpdateInterceptor extends BaseInterceptor {
    
    private static final long serialVersionUID = 1L;

    @Override
    public Object intercept(Invocation invocation) throws Throwable {

        final MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        
        Object parameter = invocation.getArgs()[1];
        BoundSql boundSql = mappedStatement.getBoundSql(parameter);
        Object parameterObject = boundSql.getParameterObject();
        
        // 获取参数对象
        if (parameterObject != null) {
        	try{
	        	Class<?> clazz = parameterObject.getClass();
	        	Boolean isNew = (Boolean)clazz.getMethod("getIsNewRecord").invoke(parameterObject);
	        	if (isNew){
	        		clazz.getMethod("preInsert").invoke(parameterObject);
	        	}else{
	        		clazz.getMethod("preUpdate").invoke(parameterObject);
	        	}
        	}catch(Exception e){
        		// 发现错误，不抛出任何异常
        	}
        }

        return invocation.proceed();
    }


    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {
        initProperties(properties);
    }
    
}
